package com.funcourse.demo.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsSender implements InitializingBean {

  DefaultProfile profile;

  @Value("${ali.sms.accesskey.id}")
  private String accessKeyId;

  @Value("${ali.sms.accesskey.secret}")
  private String accessKeySecret;

  public void sendSms(String mobile,String verifyCode) {
    IAcsClient client = new DefaultAcsClient(profile);

    CommonRequest request = new CommonRequest();
    request.setSysMethod(MethodType.POST);
    request.setSysDomain("dysmsapi.aliyuncs.com");
    request.setSysVersion("2017-05-25");
    request.setSysAction("SendSms");
    request.putQueryParameter("RegionId", "cn-hangzhou");
    request.putQueryParameter("PhoneNumbers", mobile);
    request.putQueryParameter("SignName", "冲鸭");
    request.putQueryParameter("TemplateCode", "SMS_200475440");
    request.putQueryParameter("TemplateParam", "{\"code\":\""+verifyCode+"\"}");
    try {
      CommonResponse response = client.getCommonResponse(request);
      System.out.println(response.getData());
    } catch (ServerException e) {
      e.printStackTrace();
    } catch (ClientException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    profile = DefaultProfile
        .getProfile("cn-hangzhou", accessKeyId, accessKeySecret);

  }
}
